<?php
namespace app\modules\cn\models;

use app\libs\Pager;
//use app\modules\exercise\models\ExerciseListDetail;
use yii\db\ActiveRecord;
use yii\helpers\VarDumper;

class MockAnswer extends ActiveRecord
{

    public static function tableName()
    {
        return '{{%mock_answer}}';
    }

    public static function checkAnswer($answer, $trueAnswer)
    {
        if ($answer == '') {
            return $result = '';
        } else {
            $result = 0;
            if ($answer == $trueAnswer) {
                $result = 1;
            } else {
                $answerData = explode('|', $trueAnswer);
                $answerData = self::trim_array_element($answerData);
                if (in_array($answer, $answerData)) {
                    $result = 1;
                }
            }
        }
        return $result;
    }

    /**
     * [trim_array_element description]
     * @Author don
     * @Date   2021-12-22
     * @param  [type]     $array [description]
     * @return [type]            [description]
     */
    private function trim_array_element($array)
    {
        $data = [];
        foreach ($array as $key => $value) {
            $data[] = trim($value);
        }

        return $data;
    }

//    /**
//     * @Author yoyo
//     * @Date   2021-12-22
//     */
//    public function getTime($data, $type)
//    {
//        $time = array();
//        if ($type != 5) {
//            $time[0] = self::time($type, $data['mockcate_id']);
//            $time[0]['score'] = self::score($type, $data['mockcate_id']);
//        } else {
//            $time[0] = self::time(1, $data['mockcate_id']);
//            $time[0]['score'] = self::score($type, $data['mockcate_id']);
//            $time[1] = self::time(2, $data['mockcate_id']);
//            $time[1]['score'] = self::score($type, $data['mockcate_id']);
//            $time[2] = self::time(3, $data['mockcate_id']);
//            $time[2]['score'] = self::score($type, $data['mockcate_id']);
//        }
//        return $time;
//    }

    private function time($type, $pub_id)
    {
        $public = MockPublic::find()->asArray()->where('id=' . $pub_id)->orderBy('id asc')->one();
        if ($type == 1) {
            $time['type'] = '听力';
            $start['createtime'] = $public['createTime'];
            $end = MockAnswer::find()->asArray()->where('pub_id=' . $pub_id . ' and typeid=1')->orderBy('id desc')->one();
        } elseif ($type == 2) {
            $time['type'] = '阅读';
            if ($public['type'] = 5) {
                $start = MockAnswer::find()->asArray()->where('pub_id=' . $pub_id . ' and typeid=1')->orderBy('id desc')->one();
            } else {
                $start['createtime'] = $public['createTime'];
            }
            $end = MockAnswer::find()->asArray()->where('pub_id=' . $pub_id . ' and typeid=2')->orderBy('id desc')->one();
        } else {
            $start = MockAnswer::find()->asArray()->where('pub_id=' . $pub_id . ' and typeid=2')->orderBy('id desc')->one();
            $end = MockAnswer::find()->asArray()->where('pub_id=' . $pub_id . ' and typeid=3')->orderBy('id desc')->one();
            $time['type'] = '写作';
        }
        $timeStr = $end['createtime'] - $start['createtime'];
        $time['time'] = floor($timeStr / 60) . 'm' . ($timeStr % 60) . 's';

        return $time;
    }

    public function score($type, $correct, $total)
    {
        //根据正确数得分
        if ($type != 3) {
            if ($correct< 4) {
                $score = '2';
            } elseif ($correct< 7) {
                $score = '3';
            } elseif ($correct< 10) {
                $score = '3.5';
            } elseif ($correct< 13) {
                $score = '4';
            } elseif ($correct< 16) {
                $score = '4.5';
            } elseif ($correct< 20) {
                $score = '5';
            } elseif ($correct< 20) {
                $score = '5';
            } elseif ($correct < 23) {
                $score = '5.5';
            } elseif ($correct < 27) {
                $score = '6';
            } elseif ($correct < 30) {
                $score = '6.5';
            } elseif ($correct < 33) {
                $score = '7';
            } elseif ($correct < 35) {
                $score = '7.5';
            } elseif ($correct < 37) {
                $score = '8';
            } elseif ($correct < 39) {
                $score = '8.5';
            } else {
                $score = '9';
            }
        } else {
            $score = '5';
        }
        $rate = (sprintf("%.2f", $correct / $total)) * 100;
        return ['score' => $score, 'rate' => $rate];
    }

    /**
     * @数量
     * @Author yoyo
     * @Date   2021-12-22
     */
    public function getMockDetail($data, $pub_id)
    {
        $uid = \Yii::$app->session->get('uid');
        static $arr = array();
        static $m = 0;
        foreach ($data as $key => $val) {
            $ids = explode(',', $val);
            $totalError = 0;
            $totalCorrect = 0;
            $totalNoDo = 0;
            $totalTotal = 0;
            foreach ($ids as $k => $v) {
                $name = ExerciseList::find()->asArray()->select(['content_id', 'pid', 'name', 'cate_id'])->where("content_id=$v")->orderBy('content_id asc')->one();
                $pids = ExerciseList::find()->asArray()->from('x2_exercise_list el')->select(['eld.content_id', 'el.type'])->leftJoin('x2_exercise_list_detail eld', 'eld.pid=el.content_id')->where('el.cate_id=' . $name['cate_id'] . ' and el.name="' . $name['name'] . '"')->orderBy('content_id asc')->all();
                $all = ExerciseListDetail::find()->from('x2_exercise_list_detail eld')->select('eld.*,el.numbering,el.questionType,el.type')->asArray()->leftJoin('x2_exercise_list el','el.content_id=eld.pid')->where('eld.content_id in (' . implode(',', array_column($pids, 'content_id')) . ') ')->orderBy('content_id asc')->all();
                $m=0;
                foreach ($all as $ke => $va) {
                    $tmp = MockAnswer::find()->asArray()->where("content_id={$va['content_id']} and uid=$uid and pub_id=" . $pub_id['id'])->orderBy('id desc')->one();  //typeid 听阅写口
                    $sign =MockQuestionSign::find()->asArray()->where("content_id={$va['content_id']} and uid=$uid and pub_id=" . $pub_id['id'])->one();
                    $arrList = ['pid' => $va['pid'], 'content_id' => $va['content_id'], 'userAnswer' => $tmp['answer'] != false ? $tmp['answer'] : '', 'isDo' => $tmp['answer'] == false ? 0 : 1, 'judge' => $tmp['answer'] == false ? '' : $tmp['result'], 'time' => $tmp == false ? 0 : $tmp['time'],'status'=>$sign == false ? 0 : 1];

                    if ($key == 'read') {
                        if (($va['numbering'] == 3 || $va['numbering'] == 1) && $va['questionType'] == 1) {
                            $n = !empty($va['answer']) ? strlen(trim($va['answer'])) : 1;
                            end($arr[$key]['son']);
                            $arrayKey = key($arr[$key]['son']);
                            $arr[$key]['son'] = $arr[$key]['son'] == false ? array() : $arr[$key]['son'];
                            $arr[$key]['son'] += array_fill($arrayKey + 1, $n, $arrList);
                            $arr[$key]['son'] = array_values($arr[$key]['son']);
                            $m += $n;
                        } else {
                            $arr[$key]['son'][] = $arrList;
                            $m += 1;
                        }
                    } elseif ($key == 'listen') {
                        if (($va['type'] == 3 || $va['type'] == 4) && $va['questionType'] == 1) {
                            $n = !empty($va['alternatives']) ? strlen(trim($va['alternatives'])) : strlen($va['answer']);
                            end($arr[$key]['son']);
                            $arrayKey = key($arr[$key]['son']);
                            $arr[$key]['son'] = $arr[$key]['son'] == false ? array() : $arr[$key]['son'];
                            $arr[$key]['son'] += array_fill($arrayKey + 1, $n, $arrList);
                            $arr[$key]['son'] = array_values($arr[$key]['son']);
                            $m += $n;
                        } else {
                            $arr[$key]['son'][] = $arrList;
                            $m += 1;
                        }
                    } else {
                        $arr[$key]['son'][] = $arrList;
                        $m += 1;
                    }
                }
//                $error = isset(array_count_values(array_column(array_slice($arr[$key]['son'], $k * 10, 10), 'judge'))[0]) ? array_count_values(array_column(array_slice($arr[$key]['son'], $k * 10, 10), 'judge'))[0] : 0;
//                $correct = isset(array_count_values(array_column(array_slice($arr[$key]['son'], $k * 10, 10), 'judge'))[1]) ? array_count_values(array_column(array_slice($arr[$key]['son'], $k * 10, 10), 'judge'))[1] : 0;
                $error = isset(array_count_values(array_column(array_slice($arr[$key]['son'], count($arr[$key]['son'])-$m, $m), 'judge'))[0]) ? array_count_values(array_column(array_slice($arr[$key]['son'], count($arr[$key]['son'])-$m, $m), 'judge'))[0] : 0;
                $correct = isset(array_count_values(array_column(array_slice($arr[$key]['son'], count($arr[$key]['son'])-$m, $m), 'judge'))[1]) ? array_count_values(array_column(array_slice($arr[$key]['son'], count($arr[$key]['son'])-$m, $m), 'judge'))[1] : 0;
//                $total = $key=='write' ? 2 : ($key=='listen'?10:($k==2?14:13));
                $total = $key == 'write' ? 2 : $m;
                $noDo = $total - $error - $correct;
                $type = $key == 'listen' ? 1 : ($key == 'read' ? 2 : 3);
                $score = self::score($type, $correct, $total);
                $totalError += $error;
                $totalCorrect += $correct;
                $totalNoDo += $noDo;
                $totalTotal += $total;
                $arr[$key]['part'][] = ['correct' => $correct, 'error' => $error, 'total' => $total, 'noDo' => $noDo, 'rate' => $score['rate']];
            }
            $arr[$key]['totalError'] = $totalError;
            $arr[$key]['totalCorrect'] = $totalCorrect;
            $arr[$key]['totalNoDo'] = $totalNoDo;
            $arr[$key]['totalTotal'] = $totalTotal;
            $arr[$key]['Rate'] = (sprintf("%.2f", $totalCorrect / $totalTotal)) * 100;
            $arr[$key]['score'] = self::score($type, $totalCorrect, $totalTotal);
            $arr[$key]['time'] = self::time($type, $pub_id['id']);
        }
        $arr['totalScore']= self::totalScore($arr);
        return $arr;
    }

    public function totalScore($data)
    {
        if(count($data)==3){
            $scoreArray=explode('.',sprintf($data['listen']['score']['score']+$data['read']['score']['score'])/2);
            if($scoreArray[1]=='25'||$scoreArray[1]=='50'){
                $score=$scoreArray[0]+0.5;
            } elseif($scoreArray[1]=='75'){
                $score=$scoreArray[0]<8?$scoreArray[0]+1:9;
            }else{
                $score=$scoreArray[0];
            }
        }else{
            $score=isset($data['listen']['score']['score'])?$data['listen']['score']['score']:$data['read']['score']['score'];
        }
        return $score;
    }
}
